const { daily } = require("../input");
const { getNowDay, addZerp } = require("./utils");
//计算时间差，参数格式为 YYYY-MM-DD
const diffTimeHour = (targetTime, nowTime) => {
  const diff = new Date(nowTime.replace(/-/g, "/")).getTime() - new Date(targetTime.replace(/-/g, "/")).getTime(); //日期的差值，有正负
  const absTime = Math.abs(diff); //日期差的绝对值
  const unit = diff > 0 ? "已经" : "还有"; //单位
  let formatTimeDiff = parseInt(absTime / (3600 * 1000 * 24));
  // console.log('diff', diff, 'absTime', absTime, 'unit', unit, '天数差值', absTime / (3600 * 1000 * 24), 'formatTimeDiff', formatTimeDiff);
  if (formatTimeDiff == 0) {
    //如果在今天，就显示特殊的提示
    unit = "就在";
    formatTimeDiff = "今天";
  } else {
    //否则就在后缀上加个天字
    formatTimeDiff = " " + formatTimeDiff + " 天";
  }
  return [unit, formatTimeDiff];
};

//把列表处理为字符串
module.exports = handleTimeList = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const date = getNowDay();
      console.log("今日日期为", date);
      //把今日日期转为YYYY-MM-DD的格式
      const nowTime = `${date.getFullYear()}-${date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1}-${
        date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
      }`;

      const content = ["📆纪念日:"]; //内容数组
      for (let i = 0; i < daily.data.length; i++) {
        const element = daily.data[i];
        const targetArr = element.time.split("-");
        if (targetArr.length != 3) reject("日期格式输入错误");

        if (targetArr[0] == "YYYY") {
          //如果是每年固定日期
          // console.log('今日时间',`${addZerp(date.getMonth() + 1)}-${addZerp(date.getDate())}` ,'目标时间',`${targetArr[1]}-${targetArr[2]}`);
          if (`${addZerp(date.getMonth() + 1)}-${addZerp(date.getDate())}` > `${targetArr[1]}-${targetArr[2]}`) {
            //如果今日的月日比目标日期大了，说明需要和明年的目标日期比较
            targetArr[0] = date.getFullYear() + 1; //年份从YYYY变为明年
            element.time = targetArr.join("-"); //转为字符串
          } else {
            //否则就是和今年的日期比较
            targetArr[0] = date.getFullYear(); //年份从YYYY变为今年
            element.time = targetArr.join("-"); //转为字符串
          }
        }

        //计算差值
        const timeArr = diffTimeHour(element.time, nowTime);
        content.push(`· ${element.name} <${element.time.split("-").join(".")}>\n    ${timeArr.join("")}`);
      }
      resolve(content.join("\n"));
    } catch (error) {
      reject(error.message || error);
    }
  });
};
